package com.nlp.trie.probSeg;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * 单向链表
 * @author ygsong.abcft
 *
 */
public class CnTokenLinkedList implements Iterable<CnToken>{

	private Node head, tail;
	
	public CnTokenLinkedList() {
		head = null;
		tail = null;
	}
	
	public void put(CnToken item) {
		Node t = tail;
		tail = new Node(item);
		if (head == null) {
			head = tail;
		}else {
			t.next = tail;
		}
	}
	
	/**
	 * 得到头结点
	 * @return
	 */
	public Node getHead() {
		return head;
	}
	
	/**
	 * 结点个数
	 * @return
	 */
	public int size() {
		int count = 0;
		Node t = head;
		while(t != null) {
			count++;
			t = t.next;
		}
		return count;
	}
	
	/**
	 * 遍历
	 */
	@Override
	public Iterator<CnToken> iterator() {

		return new LinkIterator(head);
	}
	
	@Override
	public String toString() {
		StringBuilder buf = new StringBuilder();
		Node pCur = head;
		while(pCur != null) {
			buf.append(pCur.item.toString());
			buf.append("\t");
			pCur = pCur.next;
		}
		return buf.toString();
	}
	private class LinkIterator implements Iterator<CnToken>{

		Node itr;
		
		public LinkIterator(Node begin) {
			itr = begin;
		}
		
		@Override
		public boolean hasNext() {
			return itr != null;
		}

		@Override
		public CnToken next() {
			if (itr == null) {
				throw new NoSuchElementException();
			}
			Node cur = itr;
			itr = itr.next;
			return cur.item;
		}
		
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	public static class Node{
		public CnToken item;
		public Node next;
		public Node(CnToken item) {
			this.item = item;
			next = null;
		}
	}

}
